

function resetDatetimeForm() {
    $('#datetime-modal-title').html('Date Input');
    $('#datetime-save-btn').html('Create Date Input');
    
    $('#datetime-type').val('date');
    $('#datetime-guideline').val('none');
    $('#datetime-placeholder').val('03/14/1989');
    $('#datetime-placeholder').attr('placeholder', '03/14/1989');
    $('#datetime-db-type').val('date');
    
    $('#datetime-form').find('.time-control').slideUp();
    $('#datetime-form').find('.timezone-control').slideUp();
    $('#datetime-form').find('.guideline-control').slideUp();

    $('#datetime-db-type').find('option.time').hide();
    $('#datetime-db-type').find('option.date').show();
    $('#datetime-db-type').find('option.datetime').show();
    
    $('#datetime-label-text').val('');
    $('#datetime-name').val('');
    $('#datetime-id').val('');
    $('#datetime-placeholder').val('');
    $('#datetime-initial-value').val('');
}

function toTimeInput() {
    resetDatetimeForm();
    $('#datetime-modal-title').html('Time Input');
    $('#datetime-save-btn').html('Create Time Input');
    $('#datetime-type').val('time');
    $('#datetime-placeholder').val('11:25 PM');
    $('#datetime-placeholder').attr('placeholder', '11:25 PM');
    $('#datetime-db-type').val('time');
    $('#datetime-form').find('.time-control').slideDown();
    $('#datetime-db-type').find('option.time').show();
    $('#datetime-db-type').find('option.date').hide();
}

function toDatetimeInput() {
    resetDatetimeForm();
    $('#datetime-modal-title').html('Date &amp; Time Input');
    $('#datetime-save-btn').html('Create Date &amp; Time Input');
    $('#datetime-type').val('datetime');
    $('#datetime-placeholder').val('03/14/1989 11:25 PM');
    $('#datetime-placeholder').attr('placeholder', '03/14/1989 11:25 PM');
    $('#datetime-db-type').val('datetime');
    $('#datetime-form').find('.time-control').slideUp();
    $('#datetime-db-type').find('option.date').hide();
}

function toDateRangeInput() {
    resetDatetimeForm();
    $('#datetime-modal-title').html('Date Range Input');
    $('#datetime-save-btn').html('Create Date Range Input');
    $('#datetime-type').val('daterange');
    $('#datetime-placeholder').val('03/14/1989 - 03/14/2014');
    $('#datetime-placeholder').attr('placeholder', '03/14/1989 - 03/14/2014');
    $('#datetime-db-type').val('daterange');
    $('#datetime-form').find('.time-control').slideUp();
}

function toDatetimeRangeInput() {
    resetDatetimeForm();
    $('#datetime-modal-title').html('Date &amp; Time Range Input');
    $('#datetime-save-btn').html('Create Date &amp; Time Range Input');
    $('#datetime-type').val('datetimerange');
    $('#datetime-placeholder').val('03/14/1989 11:25 PM - 03/14/2014 11:25 PM');
    $('#datetime-placeholder').attr('placeholder', '03/14/1989 11:25 PM - 03/14/2014 11:25 PM');
    $('#datetime-db-type').val('daterange');
    $('#datetime-form').find('.time-control').slideUp();
    $('#datetime-db-type').find('option.date').hide();
}

function toTimezoneInput() {
    resetDatetimeForm();
    $('#datetime-modal-title').html('Timezone Input');
    $('#datetime-save-btn').html('Create Timezone Input');
    $('#datetime-type').val('timezone');
    $('#datetime-placeholder').val('Timezone');
    $('#datetime-placeholder').attr('placeholder', 'Timezone');
    $('#datetime-db-type').val('timezone');
    $('#datetime-form').find('.time-control').slideUp();
    $('#datetime-db-type').find('option.date').hide();
    $('#datetime-db-type').find('option.datetime').hide();
}

$(function() {
    
    // validation rules
    var rules = {};
    rules['label']                          = set_rules('label', 'label', 'required|maxlength[6]');
    rules['label-text']                     = set_rules('label-text', 'label-text', 'required|maxlength[25]');
    rules['bold-label']                     = set_rules('bold-label', 'bold-label', 'maxlength[25]');
    rules['name']                           = set_rules('name', 'name', 'required|maxlength[50]');
    rules['id']                             = set_rules('id', 'id', 'required|maxlength[50]');
    rules['placeholder']                    = set_rules('placeholder', 'placeholder', 'maxlength[50]');
    rules['initial-value']                  = set_rules('initial-value', 'initial-value', 'maxlength[255]');
    rules['type']                           = set_rules('type', 'type', 'maxlength[25]');
    rules['format']                         = set_rules('format', 'format', 'required|maxlength[25]');
    rules['db-type']                        = set_rules('db-type', 'db-type', 'required|maxlength[25]');
    rules['min-length']                     = set_rules('min-length', 'min-length', 'numeric|maxlength[11]');
    rules['max-length']                     = set_rules('max-length', 'max-length', 'required|numeric|maxlength[11]');
    rules['show-list']                      = set_rules('show-list', 'show-list', 'maxlength[25]');
    rules['searchable']                     = set_rules('searchable', 'searchable', 'maxlength[25]');
    rules['show-api']                       = set_rules('show-api', 'show-api', 'maxlength[25]');
    rules['icon']                           = set_rules('icon', 'icon', 'required|maxlength[50]');
    rules['change-icon']                    = set_rules('change-icon', 'change-icon', 'maxlength[50]');
    rules['guideline']                      = set_rules('guideline', 'guideline', 'required|maxlength[50]');
    rules['guideline-title']                = set_rules('guideline-title', 'guideline-title', 'required|maxlength[50]');
    rules['guideline-text']                 = set_rules('guideline-text', 'guideline-text', 'required|maxlength[255]');
    rules['horizontal-size']                = set_rules('horizontal-size', 'horizontal-size', 'required|maxlength[25]');
    rules['position']                       = set_rules('position', 'position', 'required|maxlength[25]');

    // fieldset form validation
    $("#datetime-form").validate({
        errorElement: 'small',
        errorClass: 'help-block',
        rules: rules,
        errorPlacement:function(error, element) {
            element.parents('.input-size').append( '<div class="clear-fix"></div>' );
            element.parents('.input-size').append( error);
        },
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-error has-success').addClass('has-error');
        },
        success: function(label) {
            label.addClass('valid').closest('.form-group').removeClass('has-error has-success').addClass('has-success');
        }
    });
    
    resetDatetimeForm();
    
    // show/hide label controls
    $('#datetime-label').change(function() {
        if( $(this).val() === 'none' ) {
            $('#datetime-form').find('.label-control').slideUp();
        } else {
            $('#datetime-form').find('.label-control').slideDown();
        }
    });
    
    // auto fill-up datetime name and id using label text
    $('#datetime-label-text').change(function() {
        var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
        ( $('#datetime-name').val() === '' || $('#datetime-name').val() === undefined ) ? $('#datetime-name').val(textLabel) : '';
        ( $('#datetime-id').val() === '' || $('#datetime-id').val() === undefined ) ? $('#datetime-id').val(textLabel) : '';
    });
    
    // auto fill-up datetime id using name
    $('#datetime-name').change(function() {
        if( $('#datetime-label').val() === 'none' ) {
            var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
            ( $('#datetime-id').val() === '' || $('#datetime-id').val() === undefined ) ? $('#datetime-id').val(textLabel) : '';
        }
    });
    
    // show/hide icon controls
    $('#datetime-icon').change(function() {
        if( $(this).val() === 'none' ) {
            $('#datetime-form').find('.icon-control').slideUp();
        } else {
            $('#datetime-form').find('.icon-control').slideDown();
        }
    });
    
    // show/hide guideline controls
    $('#datetime-guideline').change(function() {
        if( $(this).val() === 'none' ) {
            $('#datetime-form').find('.guideline-control').slideUp();
        } else if(  $(this).val() === 'label' ) {
            $('#datetime-form').find('.guideline-control').slideDown();
            $('#datetime-guideline-title-container').slideUp();
        } else {
            $('#datetime-form').find('.guideline-control').slideDown();
        }
    });
    
    // show/hide controls
    $('#datetime-type').change(function() {
        if( $(this).val() === 'time' ) {
            toTimeInput();
        }
        if( $(this).val() === 'date' ) {
            resetDatetimeForm();
        }
        if( $(this).val() === 'datetime' ) {
            toDatetimeInput();
        }
        if( $(this).val() === 'daterange' ) {
            toDateRangeInput();
        }
        if( $(this).val() === 'datetimerange' ) {
            toDatetimeRangeInput();
        }
        if( $(this).val() === 'timezone' ) {
            toTimezoneInput();
        }
    });

    $('#datetime-save-btn').click(function(event) {
        event.preventDefault();
        $('#datetime-form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#datetime-form').valid()) {

            var values                  = $('#datetime-form').serializeJSON();
            
            // label
            var label                   = ( values['label'] !== undefined && values['label'] !== '' ) ? values['label'] : '';
            var labelPosition           = ( label !== '' || label !== 'none' ) ? ' align-' + label : 'none';
            var labelText               = ( values['label-text'] !== undefined && values['label-text'] !== '' ) ? values['label-text'] : '';
            
            // field data
            var fieldName               = ( values['name'] !== undefined && values['name'] !== '' ) ? values['name'] : '';
            var fieldId                 = ( values['id'] !== undefined && values['id'] !== '' ) ? values['id'] : '';
            var placeholder             = ( values['placeholder'] !== undefined && values['placeholder'] !== '' ) ? ' placeholder="' +values['placeholder']+ '"' : '';
            var initialValue            = ( values['initial-value'] !== undefined && values['initial-value'] !== '' ) ? ' value="' + values['initial-value'] + '"' : '';
            var type                    = ( values['type'] !== undefined && values['type'] !== '' ) ? values['type'] : '';
            var showMeridian            = ( values['format'] !== undefined && values['format'] !== '' && values['format'] === '24' ) ? false : true;
            
            // min and max length
            var minLength               = ( values['min-length'] !== undefined && values['min-length'] !== '') ? ' minlength="' + values['min-length'] + '"' : '';
            var maxLength               = ( values['max-length'] !== undefined && values['max-length'] !== '' ) ? ' maxlength="' + values['max-length'] + '"' : '';
            
            // guideline
            var guideline               = ( values['guideline'] !== undefined && values['guideline'] !== '' ) ? values['guideline'] : '';
            var guidelineTitle          = ( values['guideline-title'] !== undefined && values['guideline-title'] !== '' ) ? values['guideline-title'] : '';
            var guidelineText           = ( values['guideline-text'] !== undefined && values['guideline-text'] !== '' ) ? values['guideline-text'] : '';
            
            // size and position
            var horizontalSize          = ( values['horizontal-size'] !== undefined && values['horizontal-size'] !== '' ) ? ' ' + values['horizontal-size'] : '';
            var verticalSize            = ( values['vertical-size'] !== undefined && values['vertical-size'] !== '' )? ' ' + values['vertical-size'] : '';
            var position                = ( values['position'] !== undefined && values['position'] !== '' ) ? ' ' + values['position'] : '';
            
            // validations
            var validations             = values['validations'];
            var required                = $.inArray('required', validations) !== -1 ? ' required="true" ' : ' ';
            var requiredLabel           = ( $.inArray('required', validations) !== -1 && values['label'] !== '' && values['label'] !== 'none') ? ' *' : '';
            
            // icon
            var hasIcon                 = ( values['icon'] !== undefined &&  values['icon'] !== '' && values['icon'] !== 'none' ) ? true : false;
            var icon                    = ( values['icon'] !== undefined && values['icon'] !== '' ) ? values['icon'] : 'none';
            var changeIcon              = ( values['change-icon'] !== undefined && values['change-icon'] !== '' ) ? values['change-icon'] : '<i class="fa fa-clock-o"></i>';

            var markup = '';
            var list = $('<li class="form-group row"></li>');
            markup += '<button type="button" class="close" aria-hidden="true">&times;</button>\n';
            markup += '<label for="' +fieldId+ '" class="control-label' +labelPosition+ ' col-3">\n';
            markup += labelText + requiredLabel + '\n';
            markup += '<br><small>' +guidelineText+ '</small>\n';
            markup += '</label>\n';
            markup += '<div class="control-group col-9">\n';
            markup += '<div class="input-size' + horizontalSize + position + '">\n';
            
            if( hasIcon ) {
                markup += '<div class="input-group">';
            }
            if( hasIcon && ( icon === 'left' || icon === 'both' ) ) {
                markup += '<span class="input-group-addon">' +changeIcon+ '</span>';
            }
            
            if( type === 'timezone' ) {
                markup += '<select name="' +fieldName+ '" id="' +fieldId+ '" class="form-control' + verticalSize + '"' + placeholder + initialValue + required + minLength + maxLength + '>';
                markup += '<option value="UM12">(UTC -12:00) Baker/Howland Island</option>';
                markup += '<option value="UM11">(UTC -11:00) Samoa Time Zone, Niue</option>';
                markup += '<option value="UM10">(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti</option>';
                markup += '<option value="UM95">(UTC -9:30) Marquesas Islands</option>';
                markup += '<option value="UM9">(UTC -9:00) Alaska Standard Time, Gambier Islands</option>';
                markup += '<option value="UM8">(UTC -8:00) Pacific Standard Time, Clipperton Island</option>';
                markup += '<option value="UM7">(UTC -7:00) Mountain Standard Time</option>';
                markup += '<option value="UM6">(UTC -6:00) Central Standard Time</option>';
                markup += '<option value="UM5">(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time</option>';
                markup += '<option value="UM45">(UTC -4:30) Venezuelan Standard Time</option>';
                markup += '<option value="UM4">(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time</option>';
                markup += '<option value="UM35">(UTC -3:30) Newfoundland Standard Time</option>';
                markup += '<option value="UM3">(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay</option>';
                markup += '<option value="UM2">(UTC -2:00) South Georgia/South Sandwich Islands</option>';
                markup += '<option value="UM1">(UTC -1:00) Azores, Cape Verde Islands</option>';
                markup += '<option value="UTC">(UTC) Greenwich Mean Time, Western European Time</option>';
                markup += '<option value="UP1">(UTC +1:00) Central European Time, West Africa Time</option>';
                markup += '<option value="UP2" selected="selected">(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time</option>';
                markup += '<option value="UP3">(UTC +3:00) Moscow Time, East Africa Time</option>';
                markup += '<option value="UP35">(UTC +3:30) Iran Standard Time</option>';
                markup += '<option value="UP4">(UTC +4:00) Azerbaijan Standard Time, Samara Time</option>';
                markup += '<option value="UP45">(UTC +4:30) Afghanistan</option>';
                markup += '<option value="UP5">(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time</option>';
                markup += '<option value="UP55">(UTC +5:30) Indian Standard Time, Sri Lanka Time</option>';
                markup += '<option value="UP575">(UTC +5:45) Nepal Time</option>';
                markup += '<option value="UP6">(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time</option>';
                markup += '<option value="UP65">(UTC +6:30) Cocos Islands, Myanmar</option>';
                markup += '<option value="UP7">(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam</option>';
                markup += '<option value="UP8">(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time</option>';
                markup += '<option value="UP875">(UTC +8:45) Australian Central Western Standard Time</option>';
                markup += '<option value="UP9">(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time</option>';
                markup += '<option value="UP95">(UTC +9:30) Australian Central Standard Time</option>';
                markup += '<option value="UP10">(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time</option>';
                markup += '<option value="UP105">(UTC +10:30) Lord Howe Island</option>';
                markup += '<option value="UP11">(UTC +11:00) Magadan Time, Solomon Islands, Vanuatu</option>';
                markup += '<option value="UP115">(UTC +11:30) Norfolk Island</option>';
                markup += '<option value="UP12">(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time</option>';
                markup += '<option value="UP1275">(UTC +12:45) Chatham Islands Standard Time</option>';
                markup += '<option value="UP13">(UTC +13:00) Phoenix Islands Time, Tonga</option>';
                markup += '<option value="UP14">(UTC +14:00) Line Islands</option>';                                         
                markup += '</select>';
            } else {
                markup += '<input type="text" name="' +fieldName+ '" id="' +fieldId+ '" class="form-control' + verticalSize + '"' + placeholder + initialValue + required + minLength + maxLength + '>\n';
            }

            if( hasIcon && ( icon === 'right' || icon === 'both' ) ) {
                markup += '<span class="input-group-addon">' +changeIcon+ '</span>';
            }

            if( hasIcon ) {
                markup += '</div>';
            }
            markup += '</div>\n';
            markup += '</div>\n';
            
            list.html(markup);
            list.data('controls', values);
            
            $('#form-sortable li:first-child fieldset:first-child ul').prepend(list);
            
            // time picker
            if( type === 'time' ) {
                $('#' + fieldId).timepicker({
                    defaultTime: 'current',
                    showMeridian: showMeridian,
                    minuteStep: 1
                });
            }
            
            // date picker
            if ( type === 'date' ) {
                $('#' + fieldId).datepicker({
                    autoclose: true
                });
            }
            
            // date and time picker
            if ( type === 'datetime' ) {
                
                $('#' + fieldId).datetimepicker();
                
//                $('#' + fieldId).daterangepicker({
//                    singleDatePicker: true,
//                    timePicker: true,
//                    timePickerIncrement: 1,
//                    timePicker12Hour: true,
//                    format: 'MM/DD/YYYY hh:mm A'
//                });
            }
            
            // date range picker
            if ( type === 'daterange' ) {
                $('#' + fieldId).daterangepicker({
                    
                });
            }
            
            // date and time range picker
            if ( type === 'datetimerange' ) {
                $('#' + fieldId).daterangepicker({
                    timePicker: true,
                    timePickerIncrement: 1,
                    format: 'MM/DD/YYYY hh:mm A'
                });
            }

            $('#datetime-modal').modal('hide');

        }
        
        // submit form for validation purposes
        $('#datetime-form').submit();

    });
    
    // generic date time button
    $('#generic-datetime-btn').click(function() {
        resetDatetimeForm();
        $('#datetime-modal').modal({
            width: '95%'
        });
    });
    
    // time button
    $('#time-btn').click(function() {
        resetDatetimeForm();
        toTimeInput();
        $('#datetime-modal').modal({
            width: '95%'
        });
    });
    
    // date button
    $('#date-btn').click(function() {
        resetDatetimeForm();
        $('#datetime-modal').modal({
            width: '95%'
        });
    });
    
    // date & time button
    $('#datetime-btn').click(function() {
        resetDatetimeForm();
        toDatetimeInput();
        $('#datetime-modal').modal({
            width: '95%'
        });
    });
    
    // date range button
    $('#daterange-btn').click(function() {
        resetDatetimeForm();
        toDateRangeInput();
        $('#datetime-modal').modal({
            width: '95%'
        });
    });
    
    // date and time range button
    $('#datetimerange-btn').click(function() {
        resetDatetimeForm();
        toDatetimeRangeInput();
        $('#datetime-modal').modal({
            width: '95%'
        });
    });
    
    // timezone button
    $('#timezone-btn').click(function() {
        resetDatetimeForm();
        toTimezoneInput();
        $('#datetime-modal').modal({
            width: '95%'
        });
    });
    
});

